package modules

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"sort"
	"strconv"

	"github.com/pdfcpu/pdfcpu/pkg/api"
	"github.com/pdfcpu/pdfcpu/pkg/pdfcpu/types"
)

func SplitandAddWaterMark() {
	fileIndex := 0
	var file *os.File

	fmt.Println(os.Getwd())

	// 创建一个新的水印文件
	watermarkOutputFile, err := os.Create("./pdf/upload/output.pdf")
	if err != nil {
		log.Fatal("无法创建输出文件", err)
	}
	defer watermarkOutputFile.Close()

	// 分割PDF文件
	if err = api.SplitFile("./pdf/upload/老人与海.pdf", "./pdf/split/", 1, nil); err != nil {
		log.Fatal("拆分文件失败", err)
	}

	//打开文件夹
	entries, err := os.ReadDir("./pdf/split")
	if err != nil {
		log.Fatal(err)
	}

	//根据文件名排列文件
	sort.Slice(entries, func(i, j int) bool {
		newStr_i := entries[i].Name()[:len(entries[i].Name())-4]
		newStr_j := entries[j].Name()[:len(entries[j].Name())-4]
		newStr_i = newStr_i[13:]
		newStr_j = newStr_j[13:]
		num_i, _ := strconv.Atoi(newStr_i)
		num_j, _ := strconv.Atoi(newStr_j)
		// fmt.Println(newStr_i, newStr_j, num_i, num_j)
		return num_i < num_j
	})

	for _, entry := range entries {
		if entry.IsDir() {
			continue
		}

		filePath := filepath.Join("./pdf/split", entry.Name())

		// 读取文件内容
		if fileIndex == 1 {
			file, err = os.Open(filePath)
			if err != nil {
				log.Printf("无法读取文件 %s: %v", filePath, err)
				fileIndex++
				continue
			}
		}

		fileIndex++
	}
	defer file.Close()

	//配置水印并添加
	wm, _ := api.ImageWatermark("./pdf/upload/watermarkimg.png", "scalefactor:.8", false, false, types.POINTS)
	// conf := api.LoadConfiguration()
	//获取输出文件路径
	// filepath := fmt.Sprintf("./pdf/split/" + file.Name())
	// fmt.Println(file.Name())
	if err := api.AddWatermarksFile(file.Name(), "./pdf/upload/output.pdf", nil, wm, nil); err != nil {
		log.Fatal("文件添加水印失败", err)
	}
	log.Println("文件水印添加成功，./pdf/upload/output.pdf")
}
